﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;

namespace MShop.Core.Extensions
{
    public static class IQueryableExtensions
    {
        public static IList<SelectListItem> ConvertListItem<T>(this IQueryable<T> querable, string text, string value, object selectedValue, bool includeAll)
        {
            MultiSelectList list = null;
            if (selectedValue is IEnumerable)
            {

                list = new MultiSelectList(querable, value, text, (IEnumerable)selectedValue);
            }
            else
            {

                list = new SelectList(querable, value, text, selectedValue);
            }
            List<SelectListItem> enumerable = list.ToList();
            if (includeAll)
            {
                enumerable.Insert(0, new SelectListItem() { Text = "  ", Value = "" });
            }
            return enumerable;
        }

        public static IList<SelectListItem> ConvertListItem<T>(this IQueryable<T> querable, string text, string value, object selectedValue, SelectListItem rootSelectListItem)
        {
            MultiSelectList list = null;
            if (selectedValue is IEnumerable)
            {
                list = new MultiSelectList(querable, value, text, (IEnumerable)selectedValue);
            }
            else
            {          
                list = new SelectList(querable, value, text, selectedValue);
            }
            List<SelectListItem> enumerable = list.ToList();
            if (rootSelectListItem != null)
            {
                enumerable.Insert(0, rootSelectListItem);
            }
            return enumerable;
        }

        public static IList<SelectListItem> ConvertListItem<T>(this IQueryable<T> querable, string text, string value, object selectedValue)
        {
            return ConvertListItem<T>(querable, text, value, selectedValue, false);
        }

        public static IList<SelectListItem> ConvertListItem<T>(this IQueryable<T> querable, string text, string value)
        {
            return ConvertListItem<T>(querable, text, value, null, false);
        }
          
    }
}